library(optparse)
library(tidyverse)
library(jsonlite)
library(patchwork)
library(extrafont)

option_list <- list(
  make_option("--i", default = "AllMet_Raw.txt", type = "character", help = "metabolite data file"),
  make_option("--g", default = "group.txt", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--pc", default = "", type = "character", help = "plot config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

plotConfigJson <- fromJSON(opt$pc)
width <- plotConfigJson$layout$width %>%
  as.numeric()
height <- plotConfigJson$layout$height %>%
  as.numeric()
sampleColDf <- tibble(ClassNote = plotConfigJson$color$groups, col = plotConfigJson$color$colors)
sampleCols <- sampleColDf %>%
  deframe()
barAxisFont<-plotConfigJson$font$barAxisFont %>%
  as.numeric()
barAxisTitleFont<-plotConfigJson$font$barAxisTitleFont %>%
  as.numeric()
scatterAxisFont<-plotConfigJson$font$scatterAxisFont %>%
  as.numeric()
scatterAxisTitleFont<-plotConfigJson$font$scatterAxisTitleFont %>%
  as.numeric()
scatterTitleFont<-plotConfigJson$font$scatterTitleFont %>%
  as.numeric()
fontFamily <- plotConfigJson$font$fontFamily
baseFamily <- fontFamily
if (baseFamily == "SimSum") {
  font_import(paths = c("/usr/share/fonts/myFonts"), recursive = F, prompt = F)
}

abun.bar <- read_csv("abun.bar.csv")
diff.mean <- read_csv("diff.mean.csv")

abun.bar$variable <- factor(abun.bar$variable, levels = rev(diff.mean$var))
p1 <- ggplot(abun.bar, aes(variable, Mean, fill = ClassNote)) +
  scale_x_discrete(limits = levels(diff.mean$var)) +
  coord_flip() +
  xlab("") +
  ylab("Mean proportion (%)") +
  theme(panel.background = element_rect(fill = 'transparent'),
        panel.grid = element_blank(),
        axis.ticks.length = unit(0.4, "lines"),
        axis.ticks = element_line(color = 'black'),
        axis.line = element_line(colour = "black"),
        axis.title.x = element_text(colour = 'black', size = barAxisTitleFont, face = "bold"),
        axis.text = element_text(colour = 'black', size = barAxisFont, face = "bold"),
        legend.title = element_blank(),
        legend.text = element_text(size = 12, face = "bold", colour = "black",
                                   margin = margin(r = 20)),
        legend.position = c(0.3, 1.05),
        legend.direction = "horizontal",
        legend.key.width = unit(0.8, "cm"),
        legend.key.height = unit(0.5, "cm"))


for (i in 1:(nrow(diff.mean) - 1)) {
  p1 <- p1 + annotate('rect', xmin = i + 0.5, xmax = i + 1.5, ymin = -Inf, ymax = Inf,
                      fill = ifelse(i %% 2 == 0, 'white', 'gray95'))
}

p1 <- p1 +
  geom_bar(stat = "identity", position = "dodge", width = 0.7, colour = "black")+
  scale_fill_manual("", values = sampleCols)

diff.mean$var <- factor(diff.mean$var, levels = levels(abun.bar$variable))
p2 <- ggplot(diff.mean, aes(var, estimate, fill = ClassNote)) +
  theme(panel.background = element_rect(fill = 'transparent'),
        panel.grid = element_blank(),
        axis.ticks.length = unit(0.4, "lines"),
        axis.ticks = element_line(color = 'black'),
        axis.line = element_line(colour = "black"),
        axis.title.x = element_text(colour = 'black', size = scatterAxisTitleFont, face = "bold"),
        axis.text = element_text(colour = 'black', size = scatterAxisFont, face = "bold"),
        axis.text.y = element_blank(),
        legend.position = "none",
        axis.line.y = element_blank(),
        axis.ticks.y = element_blank(),
        plot.title = element_text(size = scatterTitleFont, face = "bold", colour = "black", hjust = 0.5)) +
  scale_x_discrete(limits = levels(diff.mean$var)) +
  coord_flip() +
  xlab("") +
  ylab("Difference in mean proportions (%)") +
  labs(title = "95% confidence intervals")

for (i in 1:(nrow(diff.mean) - 1)) {
  p2 <- p2 + annotate('rect', xmin = i + 0.5, xmax = i + 1.5, ymin = -Inf, ymax = Inf,
                      fill = ifelse(i %% 2 == 0, 'white', 'gray95'))
}

p2 <- p2 +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
                position = position_dodge(0.8), width = 0.5, size = 0.5) +
  geom_point(shape = 21, size = 3) +
  scale_fill_manual("", values = sampleCols) +
  geom_hline(aes(yintercept = 0), linetype = 'dashed', color = 'black')

p3 <- ggplot(diff.mean, aes(var, estimate, fill = ClassNote)) +
  geom_text(aes(y = 0, x = var), label = diff.mean$p.value,
            hjust = 0, fontface = "bold", inherit.aes = FALSE, size = 3) +
  geom_text(aes(x = nrow(diff.mean) / 2 + 0.5, y = 0.85), label = "P-value (corrected)",
            srt = 90, fontface = "bold", size = 5) +
  coord_flip() +
  ylim(c(0, 1)) +
  theme(panel.background = element_blank(),
        panel.grid = element_blank(),
        axis.line = element_blank(),
        axis.ticks = element_blank(),
        axis.text = element_blank(),
        axis.title = element_blank())

p <- p1 + p2 + p3 + plot_layout(widths = c(4, 6, 2))

ggsave("Stamp.pdf", p, width = width, height = height,family = baseFamily)




